<?php

declare(strict_types=1);

namespace app\model;

use think\Model;
use tools\jwt;

/**
 * @mixin \think\Model
 */
class Users extends Model
{
    // 会员模型
    protected $pk = 'uid';

    /**
     * 会员注册
     * @param string $username 用户名 
     * @param string $email 邮箱
     * @param string $password 密码
     * @return bool|array
     */
    public static function register($username, $email, $password)
    {
        $user = Users::getByEmail($email);
        if (!empty($user)) return [false, '该邮箱已注册'];

        $user = Users::create([
            'username' => $username,
            'email' => $email,
            'password' => password_hash($password, PASSWORD_DEFAULT),
            'status' => 1,
            'create_ip' => request()->ip()
        ]);

        if (!empty($user->username)) {
            return [true];
        } else {
            return [false, '注册失败,请重试'];
        }
    }

    /**
     * 会员登录
     * @param string $user 用户名或邮箱
     * @param string $password 密码
     */
    public static function login($user, $password)
    {
        $user = Users::where('username|email', $user)->find();
        if (empty($user)) return [false, '用户不存在或密码错误'];

        if (password_verify($password, $user->password)) {

            if ($user->status !== 1) {
                return [false, '用户状态错误,status:' . $user->status];
            }

            $jwt = new jwt;
            $token = $jwt->withClaim('sub', 'EvoForum')
                ->withClaim('exp', time() + 86400)
                ->withClaim('uid', $user->uid)
                ->withClaim('is_admin', $user->is_admin === 1 ? true : false)
                ->create();

            $user->login_time = time();
            $user->login_ip = request()->ip();
            $user->save();

            return [true, $token];
        } else {
            return [false, '用户不存在或密码错误'];
        }
    }
}
